package com.xjscrm.server.service.friendreq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.msg.MicaNewFriendAddMsg;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerAcceptFriendMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.FriendReqNotPassTypeEnum;
import com.xjscrm.common.enums.FriendReqStatusEnum;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.newcustmoerplan.NewCustomerPlanRule;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.DelayTopics;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.Functions;
import com.xjscrm.server.dto.wwfriendreq.WwFriendReqQuery;
import com.xjscrm.server.enums.LimitRedisCacheKeyEnum;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.friendreq.WwFriendReqService;
import com.xjscrm.server.vo.device.Device;
import com.xjscrm.server.vo.wwfriendreq.FriendReqVerifyResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信好友申请实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwFriendReqServiceImpl implements WwFriendReqService {
    @Autowired
    private WwFriendReqMapper wwFriendReqMapper;
    @Autowired
    private OperatePlanDeviceMapper operatePlanDeviceMapper;
    @Autowired
    private OperatePlanMapper operatePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    /**
     * 好友添加申请
     *
     * @param micaTransDto 好友申请实体类
     * @return 实例对象
     */
    @Async("taskExecutorForFriendReq")
    @TraceGenerate //注入消息id标签
    public void newFriendAdd(MicaTransDto micaTransDto) {
        try {

            log.info("--监控系统日志--开始--");

            MicaNewFriendAddMsg micaNewFriendAddMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaNewFriendAddMsg.class);

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //查询该机器人的配置方案
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //当前时间
            int now = DateUtil.getTime();

            OperatePlanDevice operatePlanDevice = operatePlanDeviceMapper.queryNewCustomerPlanByDeviceUniqueId(device.getId(), device.getMerId());
            if (operatePlanDevice == null) { //未配置方案，直接入库并发送通过指令
                log.info("该机器人还未配置接收新客户方案，deviceId={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
                return;
            }

            OperatePlan operatePlan = operatePlanMapper.queryById(operatePlanDevice.getPlanId());
            if (operatePlan == null) {
                log.info("该机器人配置的接收新客户方案不存在，device={}, merId={}, planId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId(), operatePlanDevice.getPlanId());
                return;
            }

            //判断好友是否存在,存在则直接修改好友请求状态
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), micaNewFriendAddMsg.getWxid());
            if (wwCustomer != null) {
                //判断是否存在该企业微信
                WwFriendReq wwFriendReq = wwFriendReqMapper.queryByDeviceIdAndWxid(micaTransDto.getDeviceId(), micaNewFriendAddMsg.getWxid(), micaTransDto.getMerId());
                if (wwFriendReq != null && Tools.getInteger(wwFriendReq.getStatus()).intValue() == FriendReqStatusEnum.HANDING.getId()) { //处理中的好友请求修改状态为已通过
                    wwFriendReq.setStatus(FriendReqStatusEnum.PASSED.getId()); //已通过
                    wwFriendReq.setOptTime(now);
                    wwFriendReq.setNotPassType(null);
                    wwFriendReq.setUpdateTime(now);
                    wwFriendReqMapper.update(wwFriendReq);
                    return;
                }
            }

            //验证符合条件
            FriendReqVerifyResult newCustomerVerifyResult = verifyPara(operatePlan, micaNewFriendAddMsg, device);
            if (newCustomerVerifyResult.isPass()) {//通过申请
                //判断是否存在该好友请求
                WwFriendReq wwFriendReq = wwFriendReqMapper.queryByDeviceIdAndWxid(micaTransDto.getDeviceId(), micaNewFriendAddMsg.getWxid(), micaTransDto.getMerId());
                if (wwFriendReq != null) { //修改
                    wwFriendReq.setHeadImg(micaNewFriendAddMsg.getHeadImg());
                    wwFriendReq.setNickName(micaNewFriendAddMsg.getNickName());
                    wwFriendReq.setCompanyName(micaNewFriendAddMsg.getCorpName());
                    wwFriendReq.setCorpId(micaNewFriendAddMsg.getCorpId());
                    wwFriendReq.setScene(Tools.getInteger(micaNewFriendAddMsg.getScene()));
                    wwFriendReq.setInviteWxid(micaNewFriendAddMsg.getInviteWxid());
                    wwFriendReq.setInviteNickName(micaNewFriendAddMsg.getInviteNickName());
                    wwFriendReq.setStatus(FriendReqStatusEnum.HANDING.getId()); //处理中
                    wwFriendReq.setSendStatus(0);//默认为发送指令
                    wwFriendReq.setOptTime(null);
                    wwFriendReq.setNotPassType(null);
                    wwFriendReq.setUpdateTime(now);
                    wwFriendReqMapper.update(wwFriendReq);
                } else {
                    wwFriendReq = new WwFriendReq();
                    wwFriendReq.setId(IdWorker.getId());
                    wwFriendReq.setMerId(micaTransDto.getMerId());
                    wwFriendReq.setDeviceUniqueId(device.getDeviceUniqueId());
                    wwFriendReq.setDeviceId(micaTransDto.getDeviceId());
                    wwFriendReq.setWxid(micaNewFriendAddMsg.getWxid());
                    wwFriendReq.setHeadImg(micaNewFriendAddMsg.getHeadImg());
                    wwFriendReq.setNickName(micaNewFriendAddMsg.getNickName());
                    wwFriendReq.setInviteWxid(micaNewFriendAddMsg.getInviteWxid());
                    wwFriendReq.setInviteNickName(micaNewFriendAddMsg.getInviteNickName());
                    wwFriendReq.setGender(micaNewFriendAddMsg.getGender());
                    wwFriendReq.setScene(micaNewFriendAddMsg.getScene());
                    wwFriendReq.setContent(micaNewFriendAddMsg.getContent());
                    wwFriendReq.setExtContent(micaNewFriendAddMsg.getExtContent());
                    wwFriendReq.setGroupWxid(micaNewFriendAddMsg.getGroupWxid());
                    wwFriendReq.setGroupName(micaNewFriendAddMsg.getGroupName());
                    wwFriendReq.setCountry(micaNewFriendAddMsg.getCountry());
                    wwFriendReq.setProvince(micaNewFriendAddMsg.getProvince());
                    wwFriendReq.setCity(micaNewFriendAddMsg.getCity());
                    wwFriendReq.setCompanyName(micaNewFriendAddMsg.getCorpName());
                    wwFriendReq.setCorpId(micaNewFriendAddMsg.getCorpId());
                    wwFriendReq.setStatus(FriendReqStatusEnum.HANDING.getId()); //处理中
                    wwFriendReq.setSendStatus(0);//默认为发送指令
                    wwFriendReq.setOptTime(null);
                    wwFriendReq.setNotPassType(null);
                    wwFriendReq.setCreateTime(now);
                    wwFriendReq.setUpdateTime(now);
                    //添加
                    wwFriendReqMapper.insert(wwFriendReq);
                }

//                //往机器人发送添加好友指令（已废弃，改为XXLJOB任务自动发送）
//                MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaNewFriendAddMsg, MicaTriggerType.TRIGGER_ACCEPT_FRIEND, Functions.fillTriggerMsg(device));
//                NewCustomerPlanRule newCustomerPlanRule = JSONObject.parseObject(operatePlan.getPlanRule(), NewCustomerPlanRule.class);
//                if (newCustomerPlanRule.getMinDelayTime() != null && newCustomerPlanRule.getMaxDelayTime() != null) {
//                    int rateMax = newCustomerPlanRule.getMaxDelayTime();
//                    int rateMin = newCustomerPlanRule.getMinDelayTime();
//                    //获取最小和最大时间的随机数（分数）
//                    int rateRandom = (int) (Math.random() * (rateMax - rateMin + 1) + rateMin);
//                    micaTriggerDto.setDelay(rateRandom); //设置延迟时间
//                    sendMsgProducer.pushMsgDelay(micaTriggerDto, DelayTopics.WW_TRIGGER_TOPIC); //发送延迟消息
//                } else {
//                    sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
//                }
            } else { //未通过申请, 需要判断未通过类型
                //判断是否存在该好友请求
                WwFriendReq wwFriendReq = wwFriendReqMapper.queryByDeviceIdAndWxid(micaTransDto.getDeviceId(), micaNewFriendAddMsg.getWxid(), micaTransDto.getMerId());
                if (wwFriendReq != null) { //修改
                    wwFriendReq.setHeadImg(micaNewFriendAddMsg.getHeadImg());
                    wwFriendReq.setNickName(micaNewFriendAddMsg.getNickName());
                    wwFriendReq.setCompanyName(micaNewFriendAddMsg.getCorpName());
                    wwFriendReq.setCorpId(micaNewFriendAddMsg.getCorpId());
                    wwFriendReq.setScene(Tools.getInteger(micaNewFriendAddMsg.getScene()));
                    wwFriendReq.setInviteWxid(micaNewFriendAddMsg.getInviteWxid());
                    wwFriendReq.setInviteNickName(micaNewFriendAddMsg.getInviteNickName());
                    wwFriendReq.setUpdateTime(now);
                    //休眠时间，将请求状态修改成处理中,需要重新发送MQ消息（已废除）
//                    if (newCustomerVerifyResult.getNotPassType() == FriendReqNotPassTypeEnum.SLEEP.getId()) {
//                        wwFriendReq.setStatus(FriendReqStatusEnum.HANDING.getId()); //处理中
//                        wwFriendReq.setOptTime(null);
//                        wwFriendReq.setNotPassType(newCustomerVerifyResult.getNotPassType());
//                        //添加
//                        wwFriendReqMapper.update(wwFriendReq);
//                        //发送服务器发送申请好友申请，延迟20分钟
//                        micaTransDto.setDelay((int) newCustomerVerifyResult.getDelay());//延迟时间
//                        sendMsgProducer.pushMsgDelay(micaTransDto, DelayTopics.WW_CONTACT_TOPIC); //发往机器人延迟消息
//                    } else {
                    wwFriendReq.setStatus(FriendReqStatusEnum.NOTPASSED.getId()); //未通过
                    wwFriendReq.setNotPassType(newCustomerVerifyResult.getNotPassType()); //未通过原因
                    wwFriendReq.setOptTime(now);
                    //添加
                    wwFriendReqMapper.update(wwFriendReq);
//                    }
                } else {
                    wwFriendReq = new WwFriendReq();
                    wwFriendReq.setId(IdWorker.getId());
                    wwFriendReq.setMerId(micaTransDto.getMerId());
                    wwFriendReq.setDeviceUniqueId(device.getDeviceUniqueId());
                    wwFriendReq.setDeviceId(micaTransDto.getDeviceId());
                    wwFriendReq.setWxid(micaNewFriendAddMsg.getWxid());
                    wwFriendReq.setHeadImg(micaNewFriendAddMsg.getHeadImg());
                    wwFriendReq.setNickName(micaNewFriendAddMsg.getNickName());
                    wwFriendReq.setInviteWxid(micaNewFriendAddMsg.getInviteWxid());
                    wwFriendReq.setInviteNickName(micaNewFriendAddMsg.getInviteNickName());
                    wwFriendReq.setGender(micaNewFriendAddMsg.getGender());
                    wwFriendReq.setScene(micaNewFriendAddMsg.getScene());
                    wwFriendReq.setContent(micaNewFriendAddMsg.getContent());
                    wwFriendReq.setExtContent(micaNewFriendAddMsg.getExtContent());
                    wwFriendReq.setGroupWxid(micaNewFriendAddMsg.getGroupWxid());
                    wwFriendReq.setGroupName(micaNewFriendAddMsg.getGroupName());
                    wwFriendReq.setCountry(micaNewFriendAddMsg.getCountry());
                    wwFriendReq.setProvince(micaNewFriendAddMsg.getProvince());
                    wwFriendReq.setCity(micaNewFriendAddMsg.getCity());
                    wwFriendReq.setCorpId(micaNewFriendAddMsg.getCorpId());
                    wwFriendReq.setCompanyName(micaNewFriendAddMsg.getCorpName());
                    wwFriendReq.setCorpId(micaNewFriendAddMsg.getCorpId());
                    wwFriendReq.setCreateTime(now);
                    wwFriendReq.setUpdateTime(now);
                    //休眠时间，将请求状态修改成处理中,需要重新发送MQ消息
//                    if (newCustomerVerifyResult.getNotPassType() == FriendReqNotPassTypeEnum.SLEEP.getId()) {
//                        wwFriendReq.setStatus(FriendReqStatusEnum.HANDING.getId()); //处理中
//                        wwFriendReq.setOptTime(null);
//                        wwFriendReq.setNotPassType(newCustomerVerifyResult.getNotPassType());
//                        //添加
//                        wwFriendReqMapper.insert(wwFriendReq);
//                        //发送服务器发送申请好友申请，延迟20分钟
//                        micaTransDto.setDelay((int) newCustomerVerifyResult.getDelay());//延迟时间
//                        sendMsgProducer.pushMsgDelay(micaTransDto, DelayTopics.WW_CONTACT_TOPIC); //发往机器人延迟消息
//                    } else {
                    wwFriendReq.setStatus(FriendReqStatusEnum.NOTPASSED.getId()); //未通过
                    wwFriendReq.setNotPassType(newCustomerVerifyResult.getNotPassType()); //未通过原因
                    wwFriendReq.setOptTime(now);
                    //添加
                    wwFriendReqMapper.insert(wwFriendReq);
//                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }
    }

    /**
     * 企业微信新客户方案验证接口
     *
     * @param operatePlan 新好友申请实体类
     * @return 实例对象
     */
    private FriendReqVerifyResult verifyPara(OperatePlan operatePlan, MicaNewFriendAddMsg micaNewFriendAddMsg, Device device) {
        //返回对象
        FriendReqVerifyResult newCustomerVerifyResult = new FriendReqVerifyResult();
        //默认为不通过
        newCustomerVerifyResult.setPass(false);
        if (operatePlan == null) {
            newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.VALID.getId());
            return newCustomerVerifyResult;
        }

        NewCustomerPlanRule newCustomerPlanRule = JSONObject.parseObject(operatePlan.getPlanRule(), NewCustomerPlanRule.class);
        if (newCustomerPlanRule == null) {
            log.info("规则为空，planId={}", operatePlan.getId());
            newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.VALID.getId());
            return newCustomerVerifyResult;
        }

        //默认黑名单不通过
        WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(device.getMerId(), micaNewFriendAddMsg.getWxid());
        if (wwCustomerBlacklist != null) { //在黑名单中
            log.info("黑名单会员，wxid={}", micaNewFriendAddMsg.getWxid());
            newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.BLACKLIST.getId());
            return newCustomerVerifyResult;
        }

        //自动通过：0不限制，1限制数量
        if (Tools.getInteger(newCustomerPlanRule.getAutoAudit()) == 1) { //启动
            Integer autoAuditCount = Tools.getInteger(newCustomerPlanRule.getAutoAuditCount());
            //获取当天的自动通过人数缓存
            String auto_audit_count_Key = String.format(RedisCacheKeyEnum.NEW_CUSTOMER_PLAN_AUTO_AUDIT_COUNT.getKey(), device.getDeviceId());
            Integer auto_audit_count_redis = (Integer) redisTemplate.opsForValue().get(auto_audit_count_Key);
            auto_audit_count_redis = Tools.getInteger(auto_audit_count_redis);
            //如果缓存中保持的上限已经大于等于配置的数量，则表示已经达到上限
            if (auto_audit_count_redis >= autoAuditCount) {
                log.info("每天已经达到上限，planId={},auto_audit_count_redis={}", operatePlan.getId(), auto_audit_count_redis);
                newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.DAYMAX.getId());
                return newCustomerVerifyResult;
            }
        }

//        //休眠开关（0关，1开）(已废弃，xxlJob自动通过的时候来判断是否机器人休眠)
//        if (Tools.getInteger(newCustomerPlanRule.getSleepSwitch()) == 1) { //启动
//            List<SleepRule> sleepRules = newCustomerPlanRule.getSleepRules();
//            if (sleepRules != null && sleepRules.size() > 0) {
//                for (SleepRule sleepRule : sleepRules) {
//                    String minTime = sleepRule.getMinTime();
//                    String maxTime = sleepRule.getMaxTime();
//                    //判断当前时间是否在自动任务开启时间区间内
//                    LocalDateTime now = LocalDateTime.now();
//                    LocalTime minTimeLocalTime = LocalTime.parse(minTime);
//                    LocalTime maxTimeLocalTime = LocalTime.parse(maxTime);
//                    LocalTime nowLocalTime = now.toLocalTime();
//                    boolean withinTimeInterval = Tools.isWithinTimeInterval(now, minTimeLocalTime, maxTimeLocalTime);
//                    //在区间内，则表示休眠
//                    if (withinTimeInterval) {
//                        long delay = Tools.betweenSeconds(nowLocalTime, minTimeLocalTime, maxTimeLocalTime);
//                        if(delay>0){
//                            log.info("当前休眠，planId={}, wxid={}, minTime={}, maxTime={}, delay={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), minTime, maxTime, delay);
//                            newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.SLEEP.getId());
//                            newCustomerVerifyResult.setDelay(delay);
//                            return newCustomerVerifyResult;
//                        }
//                    }
//                }
//            }
//        }

        //渠道
        if (Tools.getInteger(newCustomerPlanRule.getSceneType()) == 1) { //启动
            List<Integer> scenes = newCustomerPlanRule.getScenes();
            if (scenes != null && scenes.size() > 0) {
                if (!scenes.contains(micaNewFriendAddMsg.getScene())) {
                    log.info("渠道来源不符合，planId={}, wxid={}, scenes={}, scene={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), JSONObject.toJSONString(scenes), micaNewFriendAddMsg.getScene());
                    newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.SCENE.getId());
                    return newCustomerVerifyResult;
                }
            }
        }

        //性别
        if (Tools.getInteger(newCustomerPlanRule.getGenderType()) == 1) { //启动
            List<Integer> genders = newCustomerPlanRule.getGenders();
            if (genders != null && genders.size() > 0) {
                if (!genders.contains(micaNewFriendAddMsg.getGender())) {
                    log.info("性别不符合，planId={}, wxid={}, genders={}, gender={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), JSONObject.toJSONString(genders), micaNewFriendAddMsg.getGender());
                    newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.GENDER.getId());
                    return newCustomerVerifyResult;
                }
            }
        }

        //昵称
        if (Tools.getInteger(newCustomerPlanRule.getNicknameType()) == 1) { //启动
            List<String> nicknameKeys = newCustomerPlanRule.getNicknameKeys();
            if (nicknameKeys != null && nicknameKeys.size() > 0) {
                for (String nicknameKey : nicknameKeys) {
                    if (Tools.getStr(micaNewFriendAddMsg.getNickName()).contains(nicknameKey)) {
                        log.info("昵称不符合，planId={}, wxid={}, nicknameKeys={}, nickName={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), JSONObject.toJSONString(nicknameKeys), micaNewFriendAddMsg.getNickName());
                        newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.NICKNAME.getId());
                        return newCustomerVerifyResult;
                    }
                }
            }
        }

        //验证消息
        if (Tools.getInteger(newCustomerPlanRule.getVerifyMsgType()) == 1) { //启动
            List<String> verifyMsgKeys = newCustomerPlanRule.getVerifyMsgKeys();
            if (verifyMsgKeys != null && verifyMsgKeys.size() > 0) {
                for (String verifyMsgKey : verifyMsgKeys) {
                    if (Tools.getStr(micaNewFriendAddMsg.getContent()).contains(verifyMsgKey)) {
                        log.info("验证消息不符合，planId={}, wxid={}, verifyMsgKeys={}, verifyMsg={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), JSONObject.toJSONString(verifyMsgKeys), micaNewFriendAddMsg.getContent());
                        newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.VERIFYMSG.getId());
                        return newCustomerVerifyResult;
                    }
                }
            }
        }

        //企业微信
        if (Tools.getInteger(newCustomerPlanRule.getEnterpriseType()) == 1) { //全部拒绝
            if (StringUtils.isNotBlank(micaNewFriendAddMsg.getCorpId())) { //企业名称不等于空，则表示是企业会员
                log.info("企业名称不符合，planId={}, enterpriseType={}, getCorpId={}", operatePlan.getId(), "企业会员全部不通过", micaNewFriendAddMsg.getCorpId());
                newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.ENTERPRISE.getId());
                return newCustomerVerifyResult;
            }
        } else if (Tools.getInteger(newCustomerPlanRule.getEnterpriseType()) == 2) { //部分不接受
            if (StringUtils.isNotBlank(micaNewFriendAddMsg.getCorpName())) { //企业名称不等于空，则表示是企业会员
                List<String> enterpriseKyes = newCustomerPlanRule.getEnterpriseKyes();
                if (enterpriseKyes != null && enterpriseKyes.size() > 0) {
                    for (String enterpriseKye : enterpriseKyes) {
                        if (Tools.getStr(micaNewFriendAddMsg.getCorpName()).contains(enterpriseKye)) {
                            log.info("企业名称不符合，planId={}, wxid={}, enterpriseKyes={}, companyName={}", operatePlan.getId(), micaNewFriendAddMsg.getWxid(), JSONObject.toJSONString(enterpriseKyes), micaNewFriendAddMsg.getCorpName());
                            newCustomerVerifyResult.setNotPassType(FriendReqNotPassTypeEnum.ENTERPRISE.getId());
                            return newCustomerVerifyResult;
                        }
                    }
                }
            }
        }

        //验证全部通过，将结果改成true;
        newCustomerVerifyResult.setPass(true);
        return newCustomerVerifyResult;
    }

    /**
     * 处理发送好友请求任务
     *
     * @param operatePlanDevice
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForFriendReq")
    @TraceGenerate //注入消息id标签
    public void autoSendWwFriendReq(@MerId Long merId, OperatePlanDevice operatePlanDevice, OperatePlan operatePlan) {
        try {
            log.info("--监控系统日志--开始--");

            //限流key
            String taskLimitKet = "-autoSendWwFriendReq-taskLimitKey-merId=" + operatePlanDevice.getId();
            Object object = redisTemplate.opsForValue().get(taskLimitKet);
            if (object != null) {
                return;
            }
            //保存限流key
            redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 100, TimeUnit.SECONDS);

            try {
                WwDevice wwDevice = wwDeviceMapper.queryById(operatePlanDevice.getDeviceUniqueId());
                if(wwDevice == null){
                    return;
                }
                Device device = DeviceTools.transDevice(wwDevice);
                if (device == null) {
                    return;
                }

                //验证机器人的上次通过好友时间
                String deviceSendFriendReqLastAddtimeKey = String.format(LimitRedisCacheKeyEnum.WW_FRIEND_REQ_LAST_ADD_TIME.getKey(), device.getDeviceUniqueId());
                Object deviceSendFriendReqLastAddtime = redisTemplate.opsForValue().get(deviceSendFriendReqLastAddtimeKey);
                if(deviceSendFriendReqLastAddtime != null){//表示该机器人上次添加好友时间还未到，不能添加
                    return;
                }

                //查询当前所有开启的自动发圈的配置方案
                int now = DateUtil.getTime();

                WwFriendReqQuery wwFriendReqQuery = new WwFriendReqQuery();
                wwFriendReqQuery.setMerId(operatePlanDevice.getMerId());
                //状态 (0处理中，1已通过，2已忽略，3未通过)
                wwFriendReqQuery.setStatus(0); //带通过
                wwFriendReqQuery.setSendStatus(0); //未发送指令
                wwFriendReqQuery.setDeviceUniqueId(operatePlanDevice.getDeviceUniqueId());

                //查询所有的自动发圈配置记录
                Page<WwFriendReq> page = new Page<>();
                page.setCurrent(1);//只查第一页
                page.setSize(10); //每页查询10个
                page.addOrder(OrderItem.asc("create_time"));//默认创建时间升序
                Long idStart = 0L;
                List<WwFriendReq> wwFriendReqList = wwFriendReqMapper.findByList(page, wwFriendReqQuery);
                //往机器人发送添加好友指令
                int delay = 0;
                if (wwFriendReqList != null && wwFriendReqList.size() > 0) {
                    for (WwFriendReq wwFriendReq : wwFriendReqList) {
                        //限流判断
                        String rateLimitKey = "autoSendWwFriendReq-taskId=" + wwFriendReq.getId();
                        boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 1, 300);
                        if (!inRateLimit) {
                            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
                            continue;
                        }

                        try {

                            MicaTriggerAcceptFriendMsg micaTriggerAcceptFriendMsg = new MicaTriggerAcceptFriendMsg();
                            micaTriggerAcceptFriendMsg.setWxId(wwFriendReq.getWxid());
                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerAcceptFriendMsg, MicaTriggerType.TRIGGER_ACCEPT_FRIEND, Functions.fillTriggerMsg(device));
                            NewCustomerPlanRule newCustomerPlanRule = JSONObject.parseObject(operatePlan.getPlanRule(), NewCustomerPlanRule.class);
                            if (newCustomerPlanRule.getMinDelayTime() != null && newCustomerPlanRule.getMaxDelayTime() != null) {
                                int rateMax = Tools.getInteger(newCustomerPlanRule.getMaxDelayTime());
                                int rateMin = Tools.getInteger(newCustomerPlanRule.getMinDelayTime());
                                //获取最小和最大时间的随机数（秒）
                                int rateRandom = (int) (Math.random() * (rateMax - rateMin + 1) + rateMin);
                                delay = delay + rateRandom;
                                micaTriggerDto.setDelay(delay); //设置延迟时间
                                sendMsgProducer.pushMsgDelay(micaTriggerDto, DelayTopics.WW_TRIGGER_TOPIC); //发送延迟消息
                            } else {
                                sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC); //存放瞬时消息
                            }

                            //处理群发任务
                            wwFriendReq.setSendStatus(1); //已经发送指令
                            wwFriendReq.setUpdateTime(now);
                            wwFriendReqMapper.updateSendStatus(wwFriendReq);

                            //更新机器人缓存
                            redisTemplate.opsForValue().set(deviceSendFriendReqLastAddtimeKey, delay, delay, TimeUnit.SECONDS);

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                            //保存成功之后，手动删除限流redisKey
                            redisTemplate.delete(rateLimitKey);
                        }
                    }
                }
            } catch (Exception e) {
                log.info(e.getMessage(),e);
            } finally {
                //删除限流key
                redisTemplate.delete(taskLimitKet);
            }

        }catch (Exception e){
            log.error(e.getMessage() , e);
        }finally {
            log.info("--监控系统日志--结束--");
        }

    }

}
